package com.zweirm.lagee_quizing_web.controller;

import com.zweirm.lagee_quizing_web.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 浏览器安全控制器
 */
@Controller
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public class BrowserSecurityController {
    private RequestCache requestCache = new HttpSessionRequestCache();
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    // 需要身份认证逻辑
    @RequestMapping("/authentication/require")
    public String requireAuthentication(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        String msg = "登录后可以访问该页面";

        if (savedRequest != null) {
            String targetUrl = savedRequest.getRedirectUrl();
            if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowserProperties().getLoginPage());
            }
        }
        model.addAttribute("msg", msg);
        return "/login.html";
    }

    // Session过期逻辑
    @GetMapping("/session/invalid")
    public String sessionInvalid(Model model) {
        String msg = "会话已过期，请重新登陆";
        model.addAttribute("msg", msg);
        return "/login.html";
    }
}
